package com.example.kotlindemo.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.kotlindemo.R
import com.example.kotlindemo.adapter.MessageAdapter
import com.example.kotlindemo.base.BaseActivity
import com.example.kotlindemo.bean.MessageBean
import kotlinx.android.synthetic.main.activity_message.*
import kotlinx.android.synthetic.main.activity_recycler_view.*
import kotlinx.android.synthetic.main.activity_recycler_view.recyclerview

class MessageActivity : BaseActivity() {
    //lateinit关键字是用于延迟赋值的作用
    private lateinit var massageAdapter: MessageAdapter
    private var msgList = ArrayList<MessageBean>()

    companion object {
        fun show(context: Context) {
            context.startActivity(Intent(context, MessageActivity::class.java))
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_message)
        initMsg()
        //判断一个变量是否被初始化 只要是延迟变量如果在没有初始化的时候进行调用会抛出异常
        if (!::massageAdapter.isInitialized) {
            massageAdapter = MessageAdapter(msgList)
            recyclerview.apply {
                layoutManager = LinearLayoutManager(this@MessageActivity)
                adapter = massageAdapter
            }
        } else {
            massageAdapter.notifyDataSetChanged()
        }

        bt_send.setOnClickListener {
            if (et_msg.text.toString().isNotEmpty()) {
                msgList.add(MessageBean(et_msg.text.toString(), 0))
                massageAdapter.notifyItemInserted(msgList.size - 1)
                recyclerview.scrollToPosition(msgList.size - 1)
                et_msg.text.clear()
            }
        }
    }

    private fun initMsg() {
        msgList.add(MessageBean("哈哈哈", 0))
        msgList.add(MessageBean("哈哈哈", 1))
        msgList.add(MessageBean("哈哈哈", 0))
    }
}
